package com.yoshino.leetcode.oneHundred.eighteenth;

class Solution {
    private int max = 0;
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        dfs(root, 1);
        return max;
    }

    private void dfs(TreeNode cur, int dep) {
        if (cur.left == null && cur.right == null) {
            if (max < dep) {
                max = dep;
            }
            return;
        }
        if (cur.left != null) {
            dfs(cur.left, dep + 1);
        }
        if (cur.right != null) {
            dfs(cur.right, dep + 1);
        }
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (Math.abs(height(root.left) - height(root.right)) <= 1) {
            return  isBalanced(root.left) && isBalanced(root.right);
        }
        return false;
    }

    private int height(TreeNode cur) {
        if (cur == null) {
            return 0;
        } else {
            return Math.max(height(cur.left), height(cur.right)) + 1;
        }
    }
}